package com.ruis.kotboot.api.kisso

import com.baomidou.kisso.SSOConfig
import com.baomidou.kisso.SSOHelper
import com.baomidou.kisso.annotation.Action
import com.baomidou.kisso.annotation.Login
import com.baomidou.kisso.common.SSOConstants
import com.baomidou.kisso.common.util.HttpUtil
import com.baomidou.kisso.security.token.SSOToken
import com.baomidou.kisso.web.interceptor.SSOSpringInterceptor
import com.ruis.kotboot.common.util.SpringContextHolder
import com.ruis.kotboot.config.properties.RuisConfigProperties
import org.apache.commons.lang3.StringUtils
import org.springframework.web.method.HandlerMethod
import java.net.URLEncoder
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

class RuisSSOSpringInterceptor: SSOSpringInterceptor() {
    private val ssoConfig by lazy { SSOConfig.getInstance() }
    private val ruisConfig by lazy { SpringContextHolder.getBean(RuisConfigProperties::class.java) }
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        /**
         * 处理 Controller 方法
         * <p>
         * 判断 handler 是否为 HandlerMethod 实例
         * </p>
         */
        if (handler is HandlerMethod) {
            val method = handler.method
            val login = method.getAnnotation(Login::class.java)
            if (login != null) {
                if (login.action == Action.Skip) {
                    /**
                     * 忽略拦截
                     */
                    return true
                }
            }

            /**
             * 正常执行
             */
            val ssoToken = SSOHelper.getSSOToken<SSOToken>(request)
            if (ssoToken == null) {
                if (HttpUtil.isAjax(request)) {
                    /*
                     * Handler 处理 AJAX 请求
					 */
                    this.handlerInterceptor.preTokenIsNullAjax(request, response)
                    return false
                } else {
                    /*
					 * token 为空，调用 Handler 处理
					 * 返回 true 继续执行，清理登录状态并重定向至登录界面
					 */
                    if (this.handlerInterceptor.preTokenIsNull(request, response)) {
                        val reg = if(StringUtils.isBlank(ruisConfig.tomcatPath))
                            Regex("^http(s?)://([^/]*)(.*)")
                        else
                            Regex("^http(s?)://([^/]*)/([^/]*)(.*)")
                        val fds=reg.find(request.requestURL)
                        val url=fds?.groupValues?.get(fds.groupValues.size-1)
                        val callback=if(StringUtils.isBlank(url)|| StringUtils.isBlank(ssoConfig.loginUrl)) ""
                                else "?${ssoConfig.paramReturl}="+ URLEncoder.encode(ruisConfig.webHost+url,"utf-8")
                        SSOHelper.clearLogin(request, response)
                        response.sendRedirect(ruisConfig.webHost+ssoConfig.loginUrl+callback)
                    }
                    return false
                }
            } else {
                /*
				 * 正常请求，request 设置 token 减少二次解密
				 */
                request.setAttribute(SSOConstants.SSO_TOKEN_ATTR, ssoToken)
            }
        }

        /**
         * 通过拦截
         */
        return true
    }
}